package chinaums2

import (
    "fmt"
	"errors"
	//"wxsdk/utils/mapstruct"
	"github.com/astaxie/beego"
)

type RefundReq struct {
	TranType     string  `form:"TranType"`
	JavaCharset  string  `form:"JavaCharset"`
	Version      string  `form:"Version"`
	RefundNo     string  `form:"RefundNo,omitempty"`
	MerId        string  `form:"MerId"`
    OrderNo      string  `form:"OrderNo"`
    ShoppingDate string  `form:"ShoppingDate"`
	PayAmount    float32 `form:"PayAmount"`
    RefundAmount float32 `form:"RefundAmount"`
	Reserved     string  `form:"Reserved,omitempty"`
	SignMsg      string  `form:"SignMsg"`
}

type RefundRsp struct {
	Code       string `xml:"Code"`
	Message    string `xml:"Message"`
	SignMsg    string `xml:"SignMsg"`
}

func Refunds(account,terminal,outerPayId,orderId,refundType,refundAmount,description,key string)(rsp *RefundRsp, err error){

	req := new(RefundReq)
	req.Account = account
	req.Terminal = terminal
	req.PaymentId = outerPayId
	req.RefundNumber = orderId
	req.RefundType = refundType
	req.RefundAmount = refundAmount
	req.RefundDescription = description
	req.SignValue = makeRefundSign(req, key)
	reqURL := "https://query.oceanpayment.com/service/applyRefund"
	sdk := NewSDK(reqURL)
	rsp = new(RefundRsp)
	_, err = sdk.Request(req, rsp)
	if err != nil {
		beego.Debug("Oceanpay Refunds err:", err.Error())
		return
	}
	if rsp.RefundResults != "00" {
	   err = errors.New(rsp.RefundResults)
	}
	return
}

func makeRefundSign(refundPay *RefundReq, key string) string {
	str := refundPay.Account
	str += refundPay.Terminal
	str += refundPay.PaymentId
	str += refundPay.RefundNumber
	str += refundPay.RefundType
	str += refundPay.RefundAmount
	str += refundPay.RefundDescription
	str += key
	return fmt.Sprintf("%x", sHA256([]byte(str)))
}
